## Viki provides an open API with embeds urls etc
## - Required options is app (id)

require 'oj'

module Shin
  module Play
    class Viki
      
      def new
        self
      end
      
      # Fix these before running
      def before(params={})
        raise MissingArgument, "You are missing the argument 'viki_app_id' which is required to use this source." unless Shin.get[:viki_app_id] != nil
        
        # Timestamp
        params[:t] = Time.now.to_i
        
        "?app=" + Shin.get[:viki_app_id] + "&" + URI.encode_www_form(params)
      end
      
      # All <category>, params can be page=num, per_page=num etc.
      def all(category, params={})
        query = before(params)
        raise NotValid, "Not a valid category. Please check again." unless ["films", "series", "news", "artists"].include?(category)
        
        # Response
        response = Base.get('http://api.viki.io/v5/' + category + '.json' + query)

        data = Oj.load(response.body) rescue nil
        ret = {more: data['more'], response: []}
        
        # Multiple
        if data != nil
          data['response'].each do |r|
            ret[:response] << r
          end
        end
        
        
        ret.to_hashugar
      end
      
      # Search (params can be everything on the docs)
      def search(params={})
        query = before(params)
        
        # Response
        response = Base.get('http://api.viki.io/v5/search.json' + query)
        data = Oj.load(response.body) rescue nil
        ret = {more: data['more'], response: []}
        
        # Multiple
        if !data.empty? and data != nil
          data['response'].each do |r|
            ret[:response] << r
          end
        end
        
        
        ret.to_hashugar
      end
      
      # Info (can be series id, movie id, video etc)
      def info(params={})
        id = params[:id]
        query = before(params)
        
        # Response
        response = Base.get('http://api.viki.io/v5/containers/' + id.to_s + '.json' + query)
        data = Oj.load(response.body) rescue nil
        
        data.to_hashugar
      end
      
      # Episodes
      def episodes(params={})
        id = params[:id]
        query = before(params)
        
        # Response
        response = Base.get('http://api.viki.io/v5/containers/' + id.to_s + '/episodes.json' + query)
        data = Oj.load(response.body) rescue nil
        ret = {more: data['more'], response: []}
        
        # Multiple
        if !data.empty? and data != nil
          data['response'].each do |r|
            ret[:response] << r
          end
        end
        
        ret.to_hashugar
      end
      
      
      # Errors
      class NotValid         < StandardError; end
      class MissingArgument  < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end
